package com.iteaj.iot.taos;

import com.iteaj.iot.ProtocolException;
import com.iteaj.iot.ProtocolHandle;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import java.lang.reflect.Method;

public class TaosHandleProxyFactory {

    private ConfigurableListableBeanFactory beanFactory;

    public TaosHandleProxyFactory(ConfigurableListableBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public Object createProxy(TaosHandle target) {
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(target);
        try {
            TaosSqlManager sqlManager = this.beanFactory.getBean(TaosSqlManager.class);
            proxyFactory.addAdvice((MethodInterceptor) invocation -> {
                Method method = invocation.getMethod();
                if(ProtocolHandle.method.getName().equals(method.getName())) {
                    Object returnValue = invocation.proceed();
                    if(returnValue != null) {
                        sqlManager.execute(returnValue, target);
                    }

                    return returnValue;
                }

                return invocation.proceed();
            });
        } catch (Exception e) {
            throw new ProtocolException("创建Taos适配的ProtocolHandle.handle(protocol)代理失败", e);
        }

        proxyFactory.setProxyTargetClass(true);
        return proxyFactory.getProxy(target.getClass().getClassLoader());
    }
}
